import Vue from 'vue'
import VueRouter from 'vue-router'
import { Dialog } from 'vant'
import store from '@/store/'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/'),
    meta: { requiresAuth: false, title: '资讯登陆' }
  },
  {
    path: '/',
    component: () => import('@/views/layout/'),
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('@/views/home/'),
        meta: { requiresAuth: false, title: '简报首页' }
      },
      {
        path: '/search',
        name: 'search',
        component: () => import('@/views/search/'),
        meta: { requiresAuth: false, title: '资讯搜索' }
      },
      {
        path: '/append',
        name: 'append',
        component: () => import('@/views/append/'),
        meta: { requiresAuth: false, title: '发布资讯' }
      },
      {
        path: '/setting',
        name: 'setting',
        component: () => import('@/views/setting/'),
        meta: { requiresAuth: false, title: '个人中心' }
      }
    ]
  },
  {
    path: '/article/:articleId',
    name: 'article',
    component: () => import('@/views/article/'),
    props: true,
    meta: { requiresAuth: false, title: '资讯详情' }
  },
  {
    path: '/release',
    name: 'release',
    component: () => import('@/views/release'),
    meta: { requiresAuth: true, title: '我的发布' }
  },
  {
    path: '/collected',
    name: 'collected',
    component: () => import('@/views/collected'),
    meta: { requiresAuth: true, title: '我的收藏' }
  },
  {
    path: '/user/profile',
    name: 'user-profile',
    component: () => import('@/views/user-profile'),
    meta: { requiresAuth: false, title: '修改资料' }
  },
  {
    path: '/user/chat',
    name: 'user-chat',
    component: () => import('@/views/user-chat'),
    meta: { requiresAuth: true, title: '智能聊天' }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    if (store.state.user) {
      return next()
    }

    Dialog.confirm({
      title: '访问提示',
      message: '该功能需要登录才能访问，确认登录吗'
    }).then(() => {
      router.replace({
        name: 'login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      })
    }).catch(() => {
      next(false)
    })
  } else {
    next()
  }
})

export default router
